package com.charging.business.constants;

import com.charging.business.config.MinFeeManager;
import com.charging.business.exception.CustomizeException;
import com.charging.common.utils.MessageUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author JerryLu
 * @date 2024/8/7 10:23
 * @description 陕西兜底费率下载及加载线程
 */
@Component
@Slf4j
public class QinGbMinFeeThread {
    private final Logger logger = LoggerFactory.getLogger(QinGbMinFeeThread.class);
    private final MinFeeManager minFeeManager;
    @Value("${database.folder.path}")
    private String folderPath;

    @Autowired
    public QinGbMinFeeThread(MinFeeManager minFeeManager) {
        this.minFeeManager = minFeeManager;
    }

    @Async("asyncServiceExecutor")
    public Future<String> execute() throws CustomizeException {
        try {
            StringBuffer sb = new StringBuffer();
            String loadGMinFeeMsg = loadGbMinFee();
            Thread.sleep(500);
            MessageUtils.setErrorMsg(sb, loadGMinFeeMsg);
            if (sb.length() > 0) {
                throw new CustomizeException(sb.toString());
            }
        } catch (InterruptedException e) {
            // 恢复中断状态
            Thread.currentThread().interrupt();
            logger.warn("初始化获取spcRateVersion线程加载异常: " + e.getMessage());
        }
        return new AsyncResult<>("");
    }

    /**
     * 每周二周五每隔半小时更新最小费额费率版本号
     */
//    @Scheduled(cron = "1 30 * ? * 3,6")
    public void run() {
        try {
            loadGbMinFee();
        } catch (Exception e) {
            logger.error("updateGBMinFee failed：[更新兜底费率出错][{}][{}]", e.getMessage(), e.getMessage().replace("\r", " ").replace("\n", " "));
        }
    }

    /**
     * 加载本地兜底费率
     *
     * @return java.lang.String
     * @author JerryLu
     * @date 2024/8/7 10:36
     */
    public String loadGbMinFee() {

        String errMSG = "";
        File folder = new File(folderPath);
        File[] listOfFiles = folder.listFiles((dir, name) -> name.matches(".*_*\\.db3$"));

        if (listOfFiles == null || listOfFiles.length == 0) {
            errMSG = "本地费率库缺失";
            logger.warn(errMSG);
            return errMSG;
        }

        try {
            // 提取版本号并找到最新版本
            Map<String, File> versionToFileMap = new HashMap<>();
            for (File file : listOfFiles) {
                String fileName = file.getName();
                Pattern pattern = Pattern.compile("_(\\d{14})_");
                Matcher matcher = pattern.matcher(fileName);
                if (matcher.find()) {
                    String version = matcher.group(1);
                    versionToFileMap.put(version, file);
                }
            }
            // 确定当前应该使用的版本
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            String currentVersion = "";
            for (String version : versionToFileMap.keySet()) {
                LocalDateTime versionTime = LocalDateTime.parse(version, formatter);
                if (versionTime.isAfter(now) || versionTime.isEqual(now)) {
                    currentVersion = version;
                    break;
                }
            }

            if (currentVersion.isEmpty()) {
                currentVersion = Collections.max(versionToFileMap.keySet()); // 使用最新的版本
            }
            this.minFeeManager.setMinFeeVersion(currentVersion);
        } catch (Exception e) {
            logger.error("加载本地兜底费率库失败，{}", e.getMessage());
            errMSG = e.getMessage();
        }
        return errMSG;
    }
}
